//
//  ControlTemplateViewRecordController.m
//  Uhomebk
//
//  Created by 揭婧雯 on 17/3/3.
//  Copyright © 2017年 com.segi. All rights reserved.
//

#import "ControlTemplateViewRecordController.h"
#import "BaseRecordButtonView.h"

#pragma mark -
#pragma mark 录音控件【record】
#import "lame.h"
@interface ControlTemplateViewRecordController () <BaseRecordButtonViewDelegate> {
    CustomButtonView* reRecordBtn;//重录按钮
    BaseRecordButtonView* recordBtn;//按住录音按钮
    UIImageView* animageView;//录音动画
    UIImageView* animageView2;//播放录音动画
    NSTimer* atimer;
    CustomButtonView* playBtn;//点击播放按钮
}
@property (nonatomic, strong) NSString* defaultValue;
@end

@implementation ControlTemplateViewRecordController

static ControlTemplateViewRecordController* sharedManagerRecordInter = nil;

+ (ControlTemplateViewRecordController*)sharedManagerRecord
{
    sharedManagerRecordInter = [[self alloc] init];
    
    return sharedManagerRecordInter;
}

- (void)initVar
{
    _valueStr = @"";
    _param_id = [SEGUtils ValueToString:[_params valueForKey:@"attrInstId"]];
    _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self initVar];
    self.isNeedAdpterHotspot = YES;
    
    queue = [[NSOperationQueue alloc] init];
    [queue setMaxConcurrentOperationCount:1];
    
    _soundDataArray = [[NSMutableArray alloc] init];
    _soundData = [[NSMutableData alloc] init];
    
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
        //7.0第一次运行会提示，是否允许使用麦克风
        session = [AVAudioSession sharedInstance];
        NSError* sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (session == nil){
            NSLog(@"Error creating session: %@", [sessionError description]);
        }
        else{
            [session setActive:YES error:nil];
        }
    }
    
    NSString* docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSDateFormatter* nsdf2 = [[NSDateFormatter alloc] init];
    [nsdf2 setDateStyle:NSDateFormatterShortStyle];
    [nsdf2 setDateFormat:@"MMddHHmmssSSSS"];
    NSString* t2 = [nsdf2 stringFromDate:[NSDate date]];
    
    playName = [NSString stringWithFormat:@"%@/%@.pcm", docDir, t2];
    
    //录音控件配置设置
    settings = [[NSDictionary alloc] initWithObjectsAndKeys:
                [NSNumber numberWithInt:kAudioFormatLinearPCM], AVFormatIDKey,
                [NSNumber numberWithFloat:11025.0], AVSampleRateKey,
                [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
                [NSNumber numberWithInt:16], AVLinearPCMBitDepthKey,
                [NSNumber numberWithInt:AVAudioQualityLow], AVEncoderAudioQualityKey,
                //                [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                //                [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                nil];
    
    
    
    _bgMainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, TEMPLATE_HEIGHT)];
    _bgMainView.backgroundColor = kColor_W;
    self.tempBgView = _bgMainView;
    [self.view addSubview:_bgMainView];
    
    _paramId = [_params valueForKey:@"attrInstId"];
    
    ////////判断defaultValue是否有值
    if ([[_params valueForKey:@"initData"] length] > 0) {
        _defaultValue = [_params valueForKey:@"initData"];
    }
    
    ////////是否可读 0-不显示 1-显示
    if ([[SEGUtils ValueToString:[_params valueForKey:@"readable"]] isEqualToString:@"0"]) {
        _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), 0);
    }
    else {
        //线条
        UIView* lineView = [[UIView alloc] initWithFrame:CGRectMake(LINEMARGIN_LEFT, CGRectGetHeight(_bgMainView.bounds) - 0.5, CGRectGetWidth(_bgMainView.bounds), 0.5)];
        lineView.backgroundColor = kColor_L2;
        lineView.tag = 8888;
        [_bgMainView addSubview:lineView];
    }
    
    ////////是否必填 //是否可读 1-必须 0-可不填
    _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
    
    UILabel* titleLabel = [[UILabel alloc] init];
    [titleLabel setText:[_params valueForKey:@"title"]];
    [titleLabel setFont:kFont_16];
    [titleLabel setTextColor:kColor_1];
    titleLabel.numberOfLines = 0;
    titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
    [_bgMainView addSubview:titleLabel];
    [titleLabel sizeToFit];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_bgMainView.mas_left).offset(HEADSPACE);
        make.centerY.equalTo(_bgMainView.mas_centerY);
        make.width.mas_equalTo(TITLE_WIDTH);
    }];
    ////////是否可写 //是否可读 0-不可写 1-可写
    if ([[SEGUtils ValueToString:[_params valueForKey:@"writable"]] isEqualToString:@"0"]) //当writable为0时可读
    {
        //判断是否有录音
        if ([[SEGUtils ValueToString:[_params valueForKey:@"attrValue"]] length] == 0) {
            _bgMainView.frame = CGRectMake(0, 0, CGRectGetWidth(_bgMainView.bounds), 0);
        }
        //播放按钮
        playBtn = [[CustomButtonView alloc] initWithFrame:CGRectMake(CONTENTMARGIN_LEFT, 7, CGRectGetWidth(_bgMainView.bounds) - CONTENTMARGIN_LEFT - 61, 30)];
        [playBtn setHidden:NO];
        [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
        [playBtn.titleLabel setFont:kFont_16];
        [playBtn setTitleColor:kColor_1 forState:UIControlStateNormal];
        playBtn.layer.borderColor = kColor_L2.CGColor;
        playBtn.layer.borderWidth = 0.5;
        playBtn.layer.cornerRadius = 2;
        [playBtn.layer setMasksToBounds:YES];
        playBtn.tempData = _params;
        [playBtn addTarget:self action:@selector(onPlayAudioUrl:) forControlEvents:UIControlEventTouchUpInside];
        [_bgMainView addSubview:playBtn];
        
        NSArray* soundArray = @[ [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_1")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_2")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_3")] ];
        UIImage* tempImage = [soundArray objectAtIndex:0];
        
        animageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (CGRectGetHeight(playBtn.bounds) - tempImage.size.height) / 2, tempImage.size.width, tempImage.size.height)];
        animageView.animationImages = soundArray;
        animageView.animationRepeatCount = 0;
        animageView.animationDuration = 2.0;
        [playBtn addSubview:animageView];
        
        if ([_params valueForKey:@"attrValue"]) {
            [_soundDataArray addObject:[_params valueForKey:@"attrValue"]];
        }
    }
    else {
        //按钮
        recordBtn = [[BaseRecordButtonView alloc] initWithFrame:CGRectMake(CONTENTMARGIN_LEFT, 7,  CGRectGetWidth(_bgMainView.bounds) - CONTENTMARGIN_LEFT - 61, 30)];
        recordBtn.fundelegate = self;
        recordBtn.adjustsImageWhenHighlighted = NO;
        recordBtn.tag = 1000;
        [recordBtn setTitle:@"按住 说话" forState:UIControlStateNormal];
        [recordBtn.titleLabel setFont:kFont_16];
        [recordBtn setTitleColor:kColor_1 forState:UIControlStateNormal];
        recordBtn.layer.borderColor = kColor_L2.CGColor;
        recordBtn.layer.borderWidth = 0.5;
        recordBtn.layer.cornerRadius = 2;
        [recordBtn.layer setMasksToBounds:YES];
        recordBtn.tempData = _params;
        [_bgMainView addSubview:recordBtn];
        
        //录音动画
        NSArray* imageArray = @[ [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_1")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_2")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_3")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_4")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_5")] ];
        
        UIImage* tempImage = [imageArray objectAtIndex:0];
        
        animageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (CGRectGetHeight(recordBtn.bounds) - tempImage.size.height) / 2, tempImage.size.width, tempImage.size.height)];
        //        [animageView setImage:tempImage];
        animageView.animationImages = imageArray;
        animageView.animationRepeatCount = 0;
        animageView.animationDuration = 2.0;
        [recordBtn addSubview:animageView];
        
        //播放按钮
        playBtn = [[CustomButtonView alloc] initWithFrame:CGRectMake(CONTENTMARGIN_LEFT, 7,  CGRectGetWidth(_bgMainView.bounds) - CONTENTMARGIN_LEFT - 61, 30)];
        [playBtn setHidden:YES];
        [playBtn setBackgroundImage:nil forState:UIControlStateHighlighted];
        [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
        [playBtn.titleLabel setFont:kFont_16];
        [playBtn setTitleColor:kColor_1 forState:UIControlStateNormal];
        playBtn.layer.borderColor = kColor_L2.CGColor;
        playBtn.layer.borderWidth = 0.5;
        playBtn.layer.cornerRadius = 2;
        [playBtn.layer setMasksToBounds:YES];
        playBtn.tempData = _params;
        [playBtn addTarget:self action:@selector(onPlayAudioAction:) forControlEvents:UIControlEventTouchUpInside];
        [_bgMainView addSubview:playBtn];
        
        //播放动画
        NSArray* soundArray = @[ [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_1")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_2")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_volume_3")] ];
        UIImage* tempImage2 = [soundArray objectAtIndex:0];
        
        animageView2 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (CGRectGetHeight(playBtn.bounds) - tempImage2.size.height) / 2, tempImage2.size.width, tempImage2.size.height)];
        //        [animageView2 setImage:tempImage2];
        animageView2.animationImages = soundArray;
        animageView2.animationRepeatCount = 0;
        animageView2.animationDuration = 2.0;
        [playBtn addSubview:animageView2];
        
        //重录按钮
        reRecordBtn = [[CustomButtonView alloc] initWithFrame:CGRectMake(CGRectGetWidth(_bgMainView.bounds) - TEMPLATE_HEIGHT - 7, 0, TEMPLATE_HEIGHT, TEMPLATE_HEIGHT)];
        [reRecordBtn setBackgroundImage:nil forState:UIControlStateHighlighted];
        [reRecordBtn setHidden:YES];
        reRecordBtn.tempData = _params;
        [reRecordBtn setTitle:@"重录" forState:UIControlStateNormal];
        [reRecordBtn setTitleColor:kColor_S3 forState:UIControlStateNormal];
        [reRecordBtn.titleLabel setFont:kFont_16];
        [reRecordBtn addTarget:self action:@selector(onRePlayAudioAction:) forControlEvents:UIControlEventTouchUpInside];
        [_bgMainView addSubview:reRecordBtn];
    }
}

/**
 *  自定义点击按钮事件回调 【开始录音】
 */
- (void)BaseRecordButtonStartRecord:(id)sender
{
    [self onStartAudioAction:sender];
}

/**
 *  自定义点击按钮事件回调 【停止录音】
 */
- (void)BaseRecordButtonStopRecord:(id)sender
{
    [self onStopAudioAction:sender];
}

/**
 *  重新录音
 */
- (void)onRePlayAudioAction:(CustomButtonView*)sender
{
    _valueStr = @"";
    _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
    [_soundDataArray removeAllObjects];
    _soundData = nil;
    
    //销毁计时器
    [timer invalidate];
    timer = nil;
    [timer2 invalidate];
    timer2 = nil;
    [avRecorder stop];
    avRecorder = nil;
    
    [player stop];
    //隐藏播放按钮
    [playBtn setHidden:YES];
    //隐藏重录按钮
    [reRecordBtn setHidden:YES];
    //显示录音按钮
    [recordBtn setHidden:NO];
    recordBtn.backgroundColor = kColor_W;
    [recordBtn setTitle:@"按住 说话" forState:UIControlStateNormal];
    //移除动画
    [self stopRecordAnimation];

    _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
}

//开始录音动画
-(void)startRecordAnimation
{
    //录音动画
    NSArray* imageArray = @[ [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_1")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_2")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_3")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_4")], [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_mic_5")] ];
    
    UIImage* tempImage = [imageArray objectAtIndex:0];
    
    animageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (CGRectGetHeight(recordBtn.bounds) - tempImage.size.height) / 2, tempImage.size.width, tempImage.size.height)];
    //    [animageView setImage:tempImage];
    animageView.animationImages = imageArray;
    animageView.animationRepeatCount = 0;
    animageView.animationDuration = 2.0;
    [animageView startAnimating];
    [recordBtn addSubview:animageView];
}

//停止录音动画
-(void)stopRecordAnimation
{
    [animageView stopAnimating];
    animageView.hidden = YES;
    [animageView removeFromSuperview];
}

/**
 *  从服务器上播放音频
 *
 *  @param sender 按钮实例
 */
- (void)onPlayAudioUrl:(CustomButtonView*)sender
{
    //暂停播放
    if ([player isPlaying]) {
        [player stop];
        
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryRecord error:&err];//播放声音的同时停止其他应用声音
        
        [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
        
        [animageView2 stopAnimating];
        
        [animageView stopAnimating];
        
        return;
    }

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@", kClientImageRootURL, [_params valueForKey:@"attrValue"]]];
    NSData* sounddata = [NSData dataWithContentsOfURL:url];
    NSError* playerError;
    
    //播放.wav格式
   
    NSData* tempData = sounddata;
  
    player = nil;
    
    player = [[AVAudioPlayer alloc] initWithData:tempData error:&playerError];
    player.delegate = self;
    if (player == nil) {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }
    else {
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&err];
        if ([player prepareToPlay])
        {
            /**
                               *  增加播放声音通知
                               */
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopSound) name:@"STOPSOUND" object:nil];
            [player play];
            [sender setTitle:@"      播放中..." forState:UIControlStateNormal];
             [animageView startAnimating];
        }
        else
        {
            [SEGAlertView showTmepMessageWithMessage:@"读取录音文件失败"];
        }
       
    }
}

/**
 *  录音完立即切入播放录音模式
 */
- (void)onPlayAudioAction:(CustomButtonView*)sender
{
    if ([player isPlaying]) {
        [player stop];
        
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryRecord error:&err];
        
        [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
        
        [animageView2 stopAnimating];
        
        [animageView stopAnimating];
        
        return;
    }
    
    NSError* playerError;
   
    
    //播放
    player = nil;
    
    /**
             此处注意：文件路径必须为mp3格式文件路径 否则无法播放
          */
    if (_soundDataArray.count == 0) {
        [SEGAlertView showTmepMessageWithMessage:@"播放录音失败，请重试"];
        return;
    }
    NSString *sourceData = _soundDataArray[0];
    NSURL *url = [NSURL URLWithString:sourceData];
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&playerError];
    player.delegate = self;
    
    if (player == nil) {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }
    
  
    else {
        /**
         *  增加播放声音通知
         */
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopSound) name:@"STOPSOUND" object:nil];
        
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        [audioSession setActive:YES error:nil];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:&err];
        if ([player prepareToPlay])
        {
            [player play];
            animageView2.hidden = NO;
            [animageView2 startAnimating];
            [sender setTitle:@"      播放中..." forState:UIControlStateNormal];
        }
        else
        {
            [SEGAlertView showTmepMessageWithMessage:@"读取录音文件失败"];
        }
        
    }
}

//录音播放完成回调
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag
{
    if (flag) {
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        NSError* err = nil;
        [audioSession setCategory:AVAudioSessionCategoryRecord error:&err];
    }
    
    [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
    
    [animageView2 stopAnimating];
    
    [animageView stopAnimating];
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError * __nullable)error
{
    
}

/**
 *  停止录音
 *
 *  @param sender 按钮实例
 */
- (void)onStopAudioAction:(CustomButtonView*)sender
{
    
    if (timenum < 2) {
        [SEGAlertView showTmepMessageWithMessage:@"录音的时间太短"];
        [self onRePlayAudioAction:recordBtn];
        return;
    }
    
    [self updateUIWithFinishRecord];
    
    [timer invalidate];
    timer = nil;
    
    [avRecorder stop];
    avRecorder = nil;
    
    NSData* data = [NSData dataWithContentsOfFile:playName];
    
    _soundData = data;
    
    _optional = @"0";
    
    [timer2 invalidate];
    timer2 = nil;
    
    
}


//完成录音时更新UI
-(void)updateUIWithFinishRecord
{
    //显示点击播放按钮
    [playBtn setHidden:NO];
    [playBtn setBackgroundColor:kColor_W];
    [playBtn setTitle:@"点击播放" forState:UIControlStateNormal];
    
    //显示重录按钮
    [reRecordBtn setHidden:NO];
    
    //隐藏播放动画 录音按钮
    [animageView2 stopAnimating];
    [animageView2 setHidden:YES];
    [recordBtn setHidden:YES];
    
}

/**
 *  停止播放声音
 */
- (void)stopSound
{
    [player stop];
    player = nil;
}

/**
 *  定时器停止录音  录制时间为1分钟
 */
- (void)stopRecord
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"STOPSOUND" object:nil];
    
    [reRecordBtn setHidden:NO];
    
    //停止录音动画
    [self stopRecordAnimation];
    
    [playBtn setHidden:NO];
    [recordBtn setHidden:YES];
    
    [timer invalidate];
    timer = nil;
    [timer2 invalidate];
    timer2 = nil;
    
    [avRecorder stop];
    avRecorder = nil;
    
    NSData* data = [NSData dataWithContentsOfFile:playName];
    
    _soundData = data;
    _optional = @"0";
    
}

- (void)onResponseValue:(NSString*)fileStr
{
    _valueStr = fileStr;
    _optional = @"0";
}

/**
 *  开始录音
 *
 *  @param sender 按钮实例
 */
- (void)onStartAudioAction:(CustomButtonView*)sender
{
    NSString* docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSDateFormatter* nsdf2 = [[NSDateFormatter alloc] init];
    [nsdf2 setDateStyle:NSDateFormatterShortStyle];
    [nsdf2 setDateFormat:@"MMddHHmmssSSSS"];
    NSString* t2 = [nsdf2 stringFromDate:[NSDate date]];
    
    playName = [NSString stringWithFormat:@"%@/%@.pcm", docDir, t2];
    
    [sender setBackgroundColor:kColor_C];
    [sender setTitle:@"      录音中..." forState:UIControlStateNormal];
    [self startRecordAnimation];
    
    [reRecordBtn setHidden:YES];
    
    if ([self canRecord]) {
        NSError* error = nil;
        if (avRecorder == nil) {
            /**
                                   注意  第一次录音时必须设置AVAudioSessionCategoryPlayAndRecord属性  否则会有延迟
                                 */
            //设置允许录音和其他应用播放音频 -  如果第一次不设置avSession  录音会有延迟，前面3秒左右的录音将不会被录入
            AVAudioSession *avSession = [AVAudioSession sharedInstance];
            NSError *err = nil;
            [avSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
            if(err){
                NSLog(@"audioSession: %@ %ld %@", [err domain], [err code], [[err userInfo] description]);
                return;
            }
            [avSession setActive:YES error:&err];
            err = nil;
            if(err){
                NSLog(@"audioSession: %@ %ld %@", [err domain], [err code], [[err userInfo] description]);
                return;
            }
            //实例化录音类
            avRecorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:playName] settings:settings error:&error];
            avRecorder.delegate = self;
            if (avRecorder) {
                avRecorder.meteringEnabled = YES;
                [avRecorder prepareToRecord];
                [avRecorder record];
                
                timenum = 0;
                //启动定时器
                timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(stopRecord) userInfo:nil repeats:NO];
                timer2 = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(onTimerAction) userInfo:nil repeats:YES];
            }
            else {
                NSInteger errorCode = CFSwapInt32HostToBig((uint32_t)[error code]);
                NSLog(@"Error: %@ [%4.4s])", [error localizedDescription], (char*)&errorCode);
            }
        }
    }
}

- (void)onTimerAction
{
    timenum++;
}

/**
 *  录音完成回调此方法
 *
 *  @param recorder 录音实例
 *  @param flag     是否成功的标记
 */
- (void)audioRecorderDidFinishRecording:(AVAudioRecorder*)recorder successfully:(BOOL)flag
{
     if (timenum < 2)
     {
         return;
     }
    [session setActive:NO error:nil];
    AVURLAsset* audioAsset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:playName] options:nil];
    CMTime audioDuration = audioAsset.duration;
    float audioDurationSeconds = CMTimeGetSeconds(audioDuration);
    
    [timeValueLabel setText:[NSString stringWithFormat:@"%f", audioDurationSeconds]];
    
    NSString* fileName = [self audio_PCMtoMP3];
    [_soundDataArray removeAllObjects];
    if (fileName) {
        [_soundDataArray addObject:fileName];
    }
}

/**
 *  监听录音的时长
 *
 *  @param timer_ 接收NSTimer实例
 */
- (void)levelTimer:(NSTimer*)timer_
{
    //call to refresh meter values刷新平均和峰值功率,此计数是以对数刻度计量的,-160表示完全安静，0表示最大输入值
    [avRecorder updateMeters];
    const double ALPHA = 0.05;
    double peakPowerForChannel = pow(10, (0.05 * [avRecorder peakPowerForChannel:0]));
    lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
    
    NSLog(@"Average input: %f Peak input: %f Low pass results: %f", [avRecorder averagePowerForChannel:0], [avRecorder peakPowerForChannel:0], lowPassResults);
}

/**
 *  判断是否允许使用麦克风7.0新增的方法requestRecordPermission
 */
- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
        AVAudioSession* audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                }
                else {
                    bCanRecord = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[[UIAlertView alloc] initWithTitle:nil
                                                    message:@"app需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风"
                                                   delegate:nil
                                          cancelButtonTitle:@"关闭"
                                          otherButtonTitles:nil] show];
                    });
                }
            }];
        }
    }
    
    return bCanRecord;
}

/**
 *  转换音频
 */
- (NSString*)audio_PCMtoMP3
{
    NSArray* fileNameArray = [playName componentsSeparatedByString:@"//"];
    NSString* tempName = [fileNameArray objectAtIndex:[fileNameArray count] - 1];
    
   NSLog(@"沙盒路径：%@",NSHomeDirectory());
    NSLog(@"%@",[[NSBundle mainBundle] bundlePath]);
    
    
    NSString* docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString* mp3FileName = [[tempName lastPathComponent] stringByReplacingOccurrencesOfString:@".pcm" withString:@""];
    mp3FileName = [mp3FileName stringByAppendingString:@".amr"];
    
    NSString* mp3FilePath = [docDir stringByAppendingPathComponent:mp3FileName];
    
    @try {
        int read, write;
        
        FILE* pcm = fopen([playName cStringUsingEncoding:1], "rb"); //source 被转换的音频文件位置
        fseek(pcm, 4 * 1024, SEEK_CUR); //skip file header
        FILE* mp3 = fopen([mp3FilePath cStringUsingEncoding:1], "wb"); //output 输出生成的Mp3文件位置
        
        const int PCM_SIZE = 8192;
        const int MP3_SIZE = 8192;
        short int pcm_buffer[PCM_SIZE * 2];
        unsigned char mp3_buffer[MP3_SIZE];
        
        lame_t lame = lame_init();
        lame_set_in_samplerate(lame, 11025.0);
        lame_set_VBR(lame, vbr_default);
        lame_init_params(lame);
        
        do {
            read = fread(pcm_buffer, 2 * sizeof(short int), PCM_SIZE, pcm);
            if (read == 0)
                write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
            else
                write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            fwrite(mp3_buffer, write, 1, mp3);
            
        } while (read != 0);
        
        lame_close(lame);
        fclose(mp3);
        fclose(pcm);
    }
    @catch (NSException* exception) {
        NSLog(@"%@", [exception description]);
    }
    @finally {
        //        self.audioFileSavePath = mp3FilePath;
        NSLog(@"MP3生成成功: %@", mp3FilePath);
        return mp3FilePath;
    }
}

/**
 *  给录音控件填充值
 *
 *  @param valueStr 接收字符串值
 */
- (void)paddingRecordView:(NSString*)valueStr
{
    if (valueStr.length > 0) {
        playName = valueStr;
        
        NSData* data = [NSData dataWithContentsOfFile:valueStr];
        
        _soundData = data;
        
        if ([_soundData length] > 0) {
            [_soundDataArray removeAllObjects];
            [_soundDataArray addObject:playName];
            // TODO 修改了逻辑 要校验
//            [_soundDataArray addObjectsFromArray:valueStr];
            
            [self stopRecord];
            _optional = @"0";
        }
        else {
            _optional = [SEGUtils ValueToString:[_params valueForKey:@"required"]];
        }
    }
}

@end
